import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
import axios from 'axios'

// 设置axios基础URL和默认头部
axios.defaults.baseURL = 'http://localhost:8080/api'
axios.defaults.headers.common['Content-Type'] = 'application/json'

// 请求拦截器 - 简化版，无需添加token
axios.interceptors.request.use(
  config => {
    console.log(`发送${config.method.toUpperCase()}请求: ${config.baseURL}${config.url}`, config.data || config.params)
    return config
  },
  error => {
    console.error('请求拦截器错误:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器处理常见错误
axios.interceptors.response.use(
  response => {
    console.log(`响应状态: ${response.status}`, response.data)
    return response
  },
  error => {
    console.error('响应错误:', error.response || error.message)
    if (error.response && error.response.status === 401) {
      // token过期或无效，重定向到登录页
      store.dispatch('resetUser')
      router.push('/login')
    }
    return Promise.reject(error)
  }
)

const app = createApp(App)

app.config.globalProperties.$axios = axios

// 注册所有Element Plus图标
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  app.component(key, component)
}

app.use(store)
  .use(router)
  .use(ElementPlus, { size: 'default', zIndex: 3000 })
  .mount('#app') 
 